import 'dart:convert';
import 'package:aqua_plunge/http/app_manager.dart';
import 'package:aqua_plunge/model/Author.dart';
import 'package:aqua_plunge/model/followItem.dart';
import 'package:aqua_plunge/model/listItem.dart';
import 'package:aqua_plunge/model/policy.dart';
import 'package:aqua_plunge/model/userinfo.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import '../constants/constants.dart';
import '../cover/LogPvManager.dart';
import '../http/Url.dart';
import '../util/header_util.dart';

class BroadCasterDao {
  static Utf8Decoder utf8decoder = const Utf8Decoder();

  ///获取主播
  static Future<List<Author>> broadcasterWall() async {
    var httpurl = Uri.parse(AppUrl.broadcasterWallSearch);
    List<Author> datas = [];

    final body = {
      'category': "Popular",
      'isPageMode': true,
      'isRemoteImageUrl': true,
      'limit': 20,
      'page': 1,
      'tag': 'All'
    };

    final jsonString = json.encode(body);
    var headers = await HeaderUtil().getHeader();

    try {
      var response = await http.post(httpurl,
          headers: headers, body: jsonString, encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if (result['data'] != null) {
          var items = result['data'] as List<dynamic>;
          datas = items.map((json) => Author.fromJson(json)).toList();
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
    return datas;
  }

  ///用户信息接口
  static Future<UserInfo> getUserInfo(String userid) async {

    UserInfo userInfo = UserInfo();
    var uri = Uri.parse("${AppUrl.getUserInfo}?userId=$userid");
    var response = await http.get(uri, headers: await HeaderUtil().getHeader());
    String bodyString = utf8decoder.convert(response.bodyBytes);

    if (response.statusCode == 200) {
      var result = json.decode(bodyString);
      if (result['data'] != null) {
        // AppManager.setUserInfo(json.encode(result['data']));
        userInfo = UserInfo.fromJson(result['data']);
      }
    } else {
      throw Exception('"Request failed with status: ${response.statusCode}"');
    }
    return userInfo;
  }

  ///保存用户信息
  static Future saveUserInfo(
      String birthday, String country, String nickname,Function? success) async {

    var httpurl = Uri.parse(AppUrl.saveUserInfo);

    final bodyParams = {
      'about': '',
      'birthday': birthday,
      'country': country,
      'language': 'en',
      'nickname': nickname
    };
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success!= null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        success();
        debugPrint('=========${result['data']}==');
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  ///添加关注
  static Future addFriend(int followUserId, Function? success) async {
    var httpurl = Uri.parse(AppUrl.addFriend);
    final body = {'followUserId': followUserId};
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(body),
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success != null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        success();
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  ///取消关注
  static Future unFriend(int followUserId, Function? success) async {
    var httpurl = Uri.parse(AppUrl.unFriend);
    final bodyParams = {'followUserId': followUserId};
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success != null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        success();
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  ///拉黑接口
  static Future block(int broadcasterId, Function? success) async {
    var httpurl = Uri.parse(AppUrl.insertRecord);

    final body = {'broadcasterId': broadcasterId, 'complainCategory': 'Block'};

    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(body),
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success != null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if (result['data'] != null) {
          await AppManager.saveBlockList(broadcasterId);
          success();
          LogPvManager.stat(page: Constants.pageBlock);
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  ///举报接口
  static Future report(
      int broadcasterId, String complainSub, Function? success) async {
    var httpurl = Uri.parse(AppUrl.insertRecord);

    final bodyParams = {
      'broadcasterId': broadcasterId,
      'complainCategory': 'Report',
      'complainSub': complainSub
    };

    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success != null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if (result['data'] != null) {
          success();
          LogPvManager.stat(page: Constants.pageReport);
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  ///解除拉黑接口
  static Future removeBlock(int broadcasterId, Function? success) async {
    var httpurl = Uri.parse(AppUrl.removeBlock);

    final body = {'blockUserId': broadcasterId};

    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(body),
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success != null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null){
          success(result['data']);
          await AppManager.removeBlockList(broadcasterId);
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  ///拉黑列表接口
  static Future<List<listItem>> blocklist() async {
    List<listItem> list = [];
    var httpurl = Uri.parse(AppUrl.blockList);
    var headers = await HeaderUtil().getHeader();
    try {
      var response = await http.post(httpurl,
          headers: headers, encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null){
          var maps =  result['data'] as List<dynamic>;
          list = maps.map((json) => listItem.fromJson(json)).toList();
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
    return list;
  }

  ///关注列表
  static Future<List<FollowItem>> friendslist() async {
    List<FollowItem> list = [];
    var httpurl = Uri.parse(AppUrl.getfridenslist);
    final bodyParams = {'limit': 20, 'page': 1};
    try {
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        if(result['data'] != null){
          var maps = result['data'] as List<dynamic>;
          list = maps.map((json) => FollowItem.fromJson(json)).toList();
        }
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
    return list;
  }


  ///调用更新头像接口
  static Future updateAvatar(String avatarPath, Function? success) async {
    var httpurl = Uri.parse(AppUrl.updateAvatar);
    final bodyParams = {'avatarPath': avatarPath};
    try {
      // Dio dio = Dio();
      // var response = await dio.post(AppUrl.updateAvatar, data: bodyParams,options: Options(
      //   headers: await HeaderUtil().getHeader(),
      // ));
      var response = await http.post(httpurl,
          headers: await HeaderUtil().getHeader(),
          body: json.encode(bodyParams),
          encoding: const Utf8Codec());
      if (response.statusCode == 200 && success != null) {
        var result = json.decode(utf8decoder.convert(response.bodyBytes));
        debugPrint('============updateAvatar: ${result['data']}');
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      Future.error(e);
    }
  }

  static Future<Policy?> getOssPolicy() async {
    Policy policy;
    var uri = Uri.parse(AppUrl.getOssPolicy);
    var response = await http.get(uri, headers: await HeaderUtil().getHeader());
    String bodyString = utf8decoder.convert(response.bodyBytes);
    if (response.statusCode == 200) {
      var result = json.decode(bodyString);
      policy = Policy.fromJson(result['data']);
    } else {
      throw Exception('"Request failed with status: ${response.statusCode}"');
    }
    return policy;
  }

  ///上传图片到 OSS
  static Future<String> uploadAvatar(Policy data, XFile xfile) async {

    String? ossPath;
    DateTime dateTime = DateTime.now();
    String fileName = xfile.path
        .split('/')
        .last;
    String format = fileName
        .split('.')
        .last;
    int imageTimeName = dateTime.millisecondsSinceEpoch +
        (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';
    String? accessKeyId = data.accessKeyId;
    String? host = data.host;
    String? policy = data.policy;
    String? signature = data.signature;
    String? dir = data.dir;
    String? callback = data.callback;
    String? key = '$dir/$imageName';

    final file = await xfile.readAsBytes();
    var filePath = http.MultipartFile.fromBytes(
        'file', file, filename: fileName);

    FormData formData = FormData.fromMap({
      'ossaccessKeyId': accessKeyId,
      'policy': policy,
      'signature': signature,
      'callback': callback,
      'key': key,
      'file': filePath,
    });
    Dio dio = Dio();
    var response = await dio.post(host!, data: formData);
    if(response.data != null){
      if(response.data["data"]["filename"] != null){
        ossPath = response.data["data"]["filename"];
      }
    }
    return ossPath??"";
  }

}
